﻿namespace SupplyChainWeb.Service
{
    using Epicor.Mfg.Lib;
    using Erp.BO;
    using Ice.Core;
    using Ice.Lib.Framework;
    using Ice.Proxy.Lib;
    using SupplyChainWeb.Models;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Defines the <see cref="E10LoginService" />
    /// </summary>
    public class E10LoginService
    {

        private static log4net.ILog log = log4net.LogManager.GetLogger("E10LoginService");
        /// <summary>
        /// 提供web的登入
        /// </summary>
        /// <param name="EpiUserID">The EpiUserID<see cref="string"/></param>
        /// <param name="EpiPassWord">The EpiPassWord<see cref="string"/></param>
        /// <param name="HttpSession">The HttpSession<see cref="System.Web.HttpSessionStateBase"/></param>
        /// <returns>The <see cref="bool"/></returns>
        public static bool e10Lgoin(string Company,string EpiUserID, string EpiPassWord, System.Web.HttpSessionStateBase HttpSession)
        {
            bool islogin = false;
            string EpiAppUrl = System.Configuration.ConfigurationManager.AppSettings["EpiAppUrl"];
            string EpiAppConfig = System.Configuration.ConfigurationManager.AppSettings["EpiAppConfig"];
            string epiconfigpath = AppDomain.CurrentDomain.BaseDirectory + EpiAppConfig;
            //epiconfigpath =  System.Environment.CurrentDirectory + "\\EpicorDemo.sysconfig";
            //epiconfigpath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\EpicorDemo.sysconfig";
            try
            {
                using (Session e10session = new Session(EpiUserID, EpiPassWord, EpiAppUrl, Session.LicenseType.DataCollection,
                epiconfigpath))
                {
                    if (e10session != null && e10session.UserID != null && e10session.UserID.Length > 0)
                    {
                        LoginModel _LoginModel = new LoginModel();
                        _LoginModel.UserID = EpiUserID;
                        _LoginModel.Company = String.IsNullOrEmpty(Company) ? e10session.CompanyID : Company;
                        MD5 _md5 = new MD5();
                        User u = null;
                        IEnumerable<User> us = SCMDataProvider.GetUser(EpiUserID);
                        if (us.Count() > 0)
                        {
                            u = us.First<User>();
                        }
                        //if (u.CompList.Length > _LoginModel.Company.Length ) //if (u.CompList.Contains(_LoginModel.Company) == false)
                        //{
                        //    _LoginModel.Company = u.CompList;
                        //}

                        //if (u.CurComp.Equals(Company) == false)
                        if (u.CompList.Contains(Company) == false)
                        {
                            e10session.Dispose();
                            return islogin;
                        }

                        _LoginModel.Password = _md5.EncryptString(EpiPassWord, "leo");
                        _LoginModel.SecurityMgr = u.SecurityMgr;
                        if (HttpSession != null)
                        {
                            HttpSession.Remove("LoginModel");
                            HttpSession.Add("LoginModel", _LoginModel);
                        }

                        e10session.Dispose();
                        islogin = true;
                    }
                }

            }
            catch (Exception e)
            {

                log.Error(e.Message, e);
            }
            
            return islogin;
        }

        /// <summary>
        /// 提供给服务的登入方法
        /// </summary>
        /// <param name="EpiUserID"></param>
        /// <param name="EpiPassWord"></param>
        /// <param name="HttpSession"></param>
        /// <returns></returns>
        public static bool e10Lgoin2(string EpiUserID, string EpiPassWord, System.Web.SessionState.HttpSessionState HttpSession)
        {
            bool islogin = false;
            string EpiAppUrl = System.Configuration.ConfigurationManager.AppSettings["EpiAppUrl"];
            string EpiAppConfig = System.Configuration.ConfigurationManager.AppSettings["EpiAppConfig"];
            string epiconfigpath = AppDomain.CurrentDomain.BaseDirectory + EpiAppConfig;
            //epiconfigpath =  System.Environment.CurrentDirectory + "\\EpicorDemo.sysconfig";
            //epiconfigpath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\EpicorDemo.sysconfig";
            try
            {
                using (Session e10session = new Session(EpiUserID, EpiPassWord, EpiAppUrl, Session.LicenseType.DataCollection,
               epiconfigpath))
                {
                    if (e10session != null && e10session.UserID != null && e10session.UserID.Length > 0)
                    {
                        LoginModel _LoginModel = new LoginModel();
                        _LoginModel.UserID = EpiUserID;
                        _LoginModel.Company = e10session.CompanyID;//String.IsNullOrEmpty(Company)?e10session.CompanyID:Company;
                        MD5 _md5 = new MD5();
                        User u = null;
                        IEnumerable<User> us = SCMDataProvider.GetUser(EpiUserID);
                        if (us.Count() > 0)
                        {
                            u = us.First<User>();
                        }
                        if (u.CompList.Contains(_LoginModel.Company) == false)
                        {
                            _LoginModel.Company = u.CompList;
                        }

                        _LoginModel.Password = _md5.EncryptString(EpiPassWord, "leo");
                        _LoginModel.SecurityMgr = u.SecurityMgr;
                        if (HttpSession != null)
                        {
                            HttpSession.Remove("LoginModel");
                            HttpSession.Add("LoginModel", _LoginModel);
                        }

                        e10session.Dispose();
                        islogin = true;
                    }
                }
            }
            catch (Exception e)
            {

                log.Error(e.Message, e);
            }

            return islogin;
        }
        /// <summary>
        /// 没有用1、SalesOrderImpl  GetUIParams
        /// 2、SalesOrderImpl    GetNewOrderHed
        /// 3、SalesOrderImpl    OnChangeofSoldToCreditCheck
        /// 4、SalesOrderImpl    ChangeSoldToID
        /// 5、SalesOrderImpl    ChangeCustomer
        /// 6、SalesOrderImpl  ChangeSoldToContact
        /// 7、SalesOrderImpl  ChangeShipToContact
        /// 8、SalesOrderImpl  ChangeNeedByDate
        /// 9、SalesOrderImpl  MasterUpdate
        /// 10、SalesOrderImpl  CheckComplianceOrderFail
        /// 11、SalesOrderImpl  GetNewOrderDtl
        /// 12、SalesOrderImpl  ChangePartNumMaster
        /// 13、SalesOrderImpl  ChangeSellingQtyMaster
        /// 14、SalesOrderImpl  ChangeUnitPrice
        /// 15、SalesOrderImpl  MasterUpdate
        /// 16、SalesOrderImpl  CheckComplianceOrderFail
        /// </summary>
        /// <param name="HttpSession"></param>
        /// <returns></returns>
        public static bool CreateOrder(System.Web.HttpSessionStateBase HttpSession,string sugNums2,string sugnumreq)
        {
            bool success = false;
            try
            {
            string[] sugNums = sugNums2.Split(',');
            string[] sugnumreqs = sugnumreq.Split(',');

                LoginModel _LoginModel = (LoginModel)HttpSession["LoginModel"];
            MD5 _md5 = new MD5();
            string EpiUserID = _LoginModel.UserID;
            string EpiPassWord = _md5.DecryptString(_LoginModel.Password, "leo");
            string EpiAppUrl = System.Configuration.ConfigurationManager.AppSettings["EpiAppUrl"];
            string EpiAppConfig = System.Configuration.ConfigurationManager.AppSettings["EpiAppConfig"];
            string epiconfigpath = AppDomain.CurrentDomain.BaseDirectory + EpiAppConfig;
            SugPoDtl sp2 = null;
            IEnumerable<SugPoDtl> dd = SCMDataProvider.GetSugPoDtlCheckBox04(sugNums, _LoginModel.Company);//sugnum不为一导致物料描述取错
            //IEnumerable<SugPoDtl> dd = SCMDataProvider.GetSugPoDtlCheckBox04(sugNums);
            if (dd.Count()>0)
            {
                sp2 = dd.First();
            }
            else
            {
                log.Error("未在云服务器中找到建议"+sugNums);
                return success;
            }

            string MktgCampaignID = SCMDataProvider.GetCompanyMktgCampaignID(_LoginModel.Company);
                


                //SalesOrderAdapter _SalesOrderAdapter = new SalesOrderAdapter(e10session)
                //SalesOrderImpl _SalesOrderImpl = new SalesOrderImpl()
                //using (CallContext.Current.TemporarySessionCreator.SetCompanyID(sp2.Company))
                using (Session e10session = new Session(EpiUserID, EpiPassWord, EpiAppUrl, Session.LicenseType.DataCollection, epiconfigpath)) {
                    e10session.CompanyID = _LoginModel.Company;
                using (var soBO = WCFServiceSupport.CreateImpl<Erp.Proxy.BO.SalesOrderImpl>(e10session, Erp.Proxy.BO.SalesOrderImpl.UriPath))
                using (var orderdtlBO = WCFServiceSupport.CreateImpl<Erp.Proxy.BO.OrderDtlSearchImpl>(e10session, Erp.Proxy.BO.OrderDtlSearchImpl.UriPath))
                {
                    //SessionModImpl sm = new  SessionModImpl(,);
                    //sm.Session
                    //sm.SetCompany()
                    //e10session.CompanyID
                    //Add Items to a SalesOrder
                    SalesOrderDataSet soDS = new Erp.BO.SalesOrderDataSet();
                    soBO.GetNewOrderHed(soDS);
                    soDS.OrderHed[0].CustomerCustID = sp2.Company;
                    soBO.ChangeSoldToID(soDS);
                    soBO.ChangeCustomer(soDS);
                    soDS.OrderHed[0].NeedByDate = sp2.DueDate.Value;//DateTime.Parse("2019-01-01");
                    soBO.ChangeNeedByDate(soDS, "OrderHed");
                    soBO.Update(soDS);

                    foreach (SugPoDtl sp in dd)
                    { 
                        if (checkSugnumExist(sp.SugNum, orderdtlBO) == false && sugnumreq.Contains(string.Format("{0}|{1}|{2}",sp.SugNum, sp.ReqNum, sp.ReqLine)) == true)
                        {
                            soBO.GetNewOrderDtl(soDS, soDS.OrderHed[0].OrderNum);
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].PartNum = sp.VenPartNum; // "001_MPCons";
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].LineDesc = sp.LineDesc; // 添加建议物料描述
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].NeedByDate = sp2.DueDate.Value; // "001_MPCons";
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].RequestDate = sp2.DueDate.Value; // "001_MPCons";
                            soBO.ChangePartNum(soDS, false, sp.IUM);//"EA"
                            var vWarn = "";
                            soBO.ChangeSellingQuantity(soDS, false, sp.XRelQty.Value, out vWarn);
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].UnitPrice = sp.UnitPrice.Value;// 10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].DocUnitPrice = sp.UnitPrice.Value;// 10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].DocDspUnitPrice = sp.UnitPrice.Value;//10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].InUnitPrice = sp.UnitPrice.Value;//10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].DocInUnitPrice = sp.UnitPrice.Value;//10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].DspUnitPrice = sp.UnitPrice.Value;//10L;
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].MktgCampaignID = MktgCampaignID.Length>0 ? MktgCampaignID : "001";//10L;
                                                                                          //              / SugNum:123456/
                            soDS.OrderDtl[soDS.OrderDtl.Count - 1].OrderComment = sp.CommentText + String.Format("/SugNum:{0}/", sp.SugNum); ;
                            //baocunsugnum
                            soBO.ChangeUnitPrice(soDS);
                            soBO.OnChangeOfMktgCampaign(MktgCampaignID.Length > 0 ? MktgCampaignID : "001", soDS);
                            soBO.OnChangeOfMktgEvnt(MktgCampaignID.Length > 0 ? MktgCampaignID : "001" ,1, soDS);
                            soBO.Update(soDS);
                        }
                    }




                    Int32 orderNum = soDS.OrderHed[0].OrderNum;
                    if (soDS.OrderDtl.Count > 0)
                    {
                        SCMDataProvider.UpdateOrderNum(sugNums, orderNum);
                    }

                    success = true;
                }
                }
            }
            catch(Exception ex)
            {
                log.Error("销售订单创建失败" + ex.Message, ex);
                throw new Exception("销售订单创建失败"+ex.Message, ex);
            }
            return success;
        }

        private static bool checkSugnumExist(int sugNum, Erp.Proxy.BO.OrderDtlSearchImpl orderdtlBO)
        {
            bool exist = false;
            string whereClause = string.Format("OrderComment like '%{0}%'",sugNum);//OpenLAine =1
            bool morePages;
            OrderDtlSearchDataSet dtls = orderdtlBO.GetRows(whereClause, 0, 0, out morePages);
            if (dtls!=null && dtls.Tables.Count> 0 && dtls.Tables[0].Rows.Count>0)
            {
                exist = true;
            }
            return exist;
        }
    }
}
